package com.zenithmind.version.config;

import com.zenithmind.common.config.AuthInterceptorConfig;
import com.zenithmind.version.config.builder.SecurityConfigBuilder;
import com.zenithmind.version.config.properties.VersionSecurityProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 版本控制服务安全配置 - 遵循依赖倒置原则，依赖抽象而非具体实现
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class VersionSecurityConfig {

    private final VersionSecurityProperties securityProperties;
    private final SecurityConfigBuilder securityConfigBuilder;

    /**
     * 版本控制服务安全配置 - 使用构建器模式，遵循开闭原则
     */
    @Bean
    @Order(1)
    public SecurityFilterChain versionSecurityFilterChain(HttpSecurity http) throws Exception {
        return securityConfigBuilder.buildSecurityFilterChain(http);
    }

    /**
     * 配置认证拦截器的跳过路径 - 使用配置属性，遵循依赖倒置原则
     * 确保Spring Security和认证拦截器使用相同的跳过路径
     */
    @Bean
    public BeanPostProcessor versionAuthPropertiesPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof AuthInterceptorConfig.AuthProperties && "authProperties".equals(beanName)) {
                    AuthInterceptorConfig.AuthProperties properties = (AuthInterceptorConfig.AuthProperties) bean;
                    properties.setSkipPaths(securityProperties.getPublicEndpoints());
                    log.info("已为版本控制服务认证拦截器设置统一的跳过路径配置，路径数量: {}",
                            securityProperties.getPublicEndpoints().size());
                }
                return bean;
            }
        };
    }
}
